﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//using System.Net.Mail;
using System.Net.Mime;
using System.IO;
using MimeKit;
using MailKit.Net.Smtp;
using MailKit.Net.Proxy;

namespace Furion.Extras.Admin.NET.Components.EMail
{
    public static class EmailHelper
    {
        ///// <summary>
        ///// 
        ///// </summary>
        ///// <param name="mailHost">送邮件的服务器地址或IP，如smtp.163.com、smtp.qq.com</param>
        ///// <param name="mailName">发件人邮箱用户名/账号</param>
        ///// <param name="mailPassWord">发件人邮箱密码</param>
        ///// <param name="subject">邮件主题</param>
        ///// <param name="tomail">收件人邮箱地址</param>
        ///// <param name="ccmail">抄送人邮箱地址</param>
        ///// <param name="bodyMessage">邮件内容</param>
        ///// <param name="attachments">附件路径</param>
        //public static void Sendmail(string mailHost, string mailName, string mailPassWord, string subject, string[] tomail, string[] ccmail, string bodyMessage, Dictionary<string, Stream> attachments)
        //{
        //    var smtpClient = new SmtpClient();
        //    var mailMessage = new MailMessage();
        //    smtpClient.EnableSsl = true;
        //    smtpClient.Host = mailHost;//指定发送邮件的服务器地址或IP，如smtp.163.com、smtp.qq.com
        //    var mailname = mailName;//发件人邮箱用户名
        //    var mailpsd = mailPassWord;//发件人邮箱密码
        //    smtpClient.Port = 25;//指定发送邮件端口 25
        //    smtpClient.UseDefaultCredentials = false;
        //    smtpClient.Credentials = new System.Net.NetworkCredential(mailname, mailpsd);
        //    smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
        //    mailMessage.BodyEncoding = Encoding.UTF8;
        //    mailMessage.IsBodyHtml = true;//是否为html格式 
        //    mailMessage.Priority = MailPriority.High;//发送邮件的优先等级 
        //    mailMessage.From = new MailAddress(mailname);
        //    foreach (var item in tomail)
        //    {
        //        mailMessage.To.Add(item);
        //    }
        //    if (ccmail != null)
        //    {
        //        foreach (var item in ccmail)
        //        {
        //            mailMessage.CC.Add(item);
        //        }
        //    }
        //    mailMessage.Subject = subject;//邮件主题 

        //    //添加邮件附件，可发送多个文件
        //    mailMessage.Attachments.Clear();
        //    if (attachments != null)
        //    {
        //        foreach (var item in attachments)
        //        {
        //            //mailMessage.Attachments.Add(new Attachment(item.ToString(), MediaTypeNames.Application.Octet));
        //            var a = new Attachment(item.Value, item.Key);
        //            mailMessage.Attachments.Add(a);
        //        }
        //    }

        //    mailMessage.Body = bodyMessage;//邮件内容
        //    try
        //    {
        //        smtpClient.Send(mailMessage);
        //    }
        //    catch (SmtpException ex)
        //    {
        //        throw new Exception("邮箱异常！" + ex.Message);
        //    }
        //}

        /// <summary>
        /// 发邮件
        /// </summary>
        /// <param name="config"></param>
        /// <param name="tos"></param>
        /// <param name="subject"></param>
        /// <param name="message"></param>
        /// <param name="attachments"></param>
        /// <returns></returns>
        public static void SendEmail(EmailConfig config, List<MailAddress> tos, string subject, string message, params string[] attachments)
        {
            try
            {
                var emailMessage = new MimeMessage();

                emailMessage.From.Add(config.From);
                foreach (var to in tos)
                    emailMessage.To.Add(to as MailAddress);

                emailMessage.Subject = subject;

                var alternative = new Multipart("alternative");
                if (config.IsHtml)
                    alternative.Add(new TextPart("html") { Text = message });
                else
                    alternative.Add(new TextPart("plain") { Text = message });

                if (attachments != null)
                {
                    foreach (string f in attachments)
                    {
                        var attachment = new MimePart()//("image", "png")
                        {
                            Content = new MimeContent(File.OpenRead(f), ContentEncoding.Default),
                            ContentDisposition = new MimeKit.ContentDisposition(MimeKit.ContentDisposition.Attachment),
                            ContentTransferEncoding = ContentEncoding.Base64,
                            FileName = Path.GetFileName(f)
                        };
                        alternative.Add(attachment);
                    }
                }
                emailMessage.Body = alternative;

                using (var client = new SmtpClient())
                {
                    if (config.IsProxy)
                        client.ProxyClient = new HttpProxyClient(config.ProxyHost, config.ProxyPort);

                    client.Connect(config.Host, config.Port, config.UseSsl);// SecureSocketOptions.None
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    client.Authenticate(config.MailFromAccount, config.MailPassword);
                    client.Send(emailMessage);
                    client.Disconnect(true);
                }
            }
            catch (Exception ex)
            {

            }
        }
    }
}

